<template>
	<view class="hao-bigbox">
		<!-- 搜索 -->
		<view class="hao-search" v-if="isSearch">
			<view class="hao-searchCent">
				<image src="/static/haoIndexListImg/search.png" class="hao-searchImg"></image>
				<input type="text" v-model="inputKey" @input="searchInput" placeholder="搜索城市/区县"
					class="hao-searchInput" />
			</view>
		</view>
		<!-- 搜索内容 -->
		<view v-if="isSearch && searchList.length > 0" class="hao-searchScroll">
			<scroll-view scroll-y style="width:100%;height:100%;">
				<view>
					<view class="hao-secondEach" v-for="(item,index) in searchList" :key="item[idValue]"
						@tap="selectIndex(item)">
						<view class="hao-avatar" v-if="isAvatar">
							<image :src="item[avatarValue]" class="hao-avatarImg"></image>
						</view>
						<view class="hao-text">
							<view class="hao-name">{{item[nameValue]}}</view>
							<view class="hao-fu" v-if="isFu">{{item[fuValue]}}</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="titleTabs" v-if="searchList.length === 0">
			<v-tabs v-model="current" field="name" :tabs="cityTabs" @change="changeTab" class="box_2_tabs"
				color="#666666" activeColor="#333333" :bold="true" paddingItem="0 24rpx" height="88rpx"
				:lineScale="0.5"></v-tabs>
		</view>

		<!-- 右侧索引 -->
		<view class="hao-letters" v-if="isLetters&&searchList.length <= 0&&isShowScroll"
			:style="{'top':isSearch?'80rpx':'0rpx','height':isSearch?'calc(100% - 80rpx)':'100%'}">
			<view class="hao-letterTop" @tap="goTop">热门</view>
			<view v-for="(item,index) in letters" :key="item"
				:style="{'height':indexEachHH+'rpx','background-color':(currentCeiling==index&&isIndexAc)?indexAcColor:''}"
				class="hao-lettersEach" :class="(currentCeiling==index&&isIndexAc)?'hao-lettersEachAc':''"
				@touchmove="handleTouchMove" @touchend="handleTouchEnd(item,index)"
				@tap="handleLetterClick(item,index)">
				{{item}}
			</view>
		</view>

		<!-- 提示当前索引 -->
		<view class="hao-toastIndex" v-if="isIndexToast && toastIndex">{{toastIndex}}</view>

		<!-- 吸顶 -->
		<view class="ceiling"
			v-if="currentCeiling !== null&&isCeil&&listInfo.length>0&&searchList.length <= 0&&isOkCurrent"
			:style="{'top':isSearch?'110rpx':'0rpx'}">{{listInfo[currentCeiling].id.split('-')[1]}}</view>

		<!-- 列表 -->
		<scroll-view scroll-y class="hao-scroll" @scroll="listenScroll" :scroll-top="scrollTop"
			:scroll-into-view="scrollEachId" v-show="searchList.length <= 0"
			:style="{'top':isSearch?'184rpx':'0rpx','height':isSearch?'calc(100% - 184rpx)':'100%'}">
			<view>
				<view class="hao-modu" v-if="isCurrentCity || isHotCity">
					<view class="hao-current" v-if="isCurrentCity">
						<view class="hao-moduTitle">当前城市</view>
						<view class="hao-currentBox">
							<view class="hao-currentLs">
								<image :src="`${$ImgBaseUrl}map.png`" class="hao-currentImg"></image>
								<view class="hao-currentCity" @tap="selectIndex(locationCity)">
									{{locationCity.cityName || '定位中...'}}
								</view>
							</view>
						</view>
					</view>
					<!-- <view class="hao-current" v-if="isCurrentCity && currentCity.cityName">
						<view class="hao-moduTitle">当前选择</view>
						<view class="hao-currentBox">
							<view class="hao-currentLs">
								<view class="hao-currentCity" @tap="selectIndex(currentCity)">
									{{currentCity.cityName}}
								</view>
							</view>
						</view>
					</view> -->
					<view class="hao-hotCity" v-if="isHotCity && hotCity.length>0">
						<view class="hao-moduTitle">热门城市</view>
						<view class="hao-hotCityBox">
							<view v-for="(item,index) in hotCity" :key="item[idValue]" @tap="selectIndex(item)"
								class="hao-hotEachCity">{{item[nameValue]}}</view>
						</view>
					</view>
				</view>

				<view v-for="(item,index) in cityList" :key="index" class="hao-each" v-if="isShowScroll">
					<view class="hao-eachTitle" :id="'hao-'+index">{{index}}</view>
					<view class="hao-second">
						<view v-for="(ite,ind) in item" :key="ite[idValue]" class="hao-secondEach"
							@tap="selectIndex(ite)">
							<view class="hao-avatar" v-if="isAvatar">
								<image :src="ite[avatarValue]" class="hao-avatarImg"></image>
							</view>
							<view class="hao-text">
								<view class="hao-name">{{ite[nameValue]}}</view>
								<view class="hao-fu" v-if="isFu">{{ite[fuValue]}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: 'hao-indexList',
		data() {
			return {
				inputKey: '',
				searchTimeout: null,
				searchList: [],
				scrollEachId: 'all',
				toastIndex: '',
				indexEachHH: 36,
				afterConverHH: 0,
				indexFirstTT: 0,
				indexLastBB: 0,
				isOk: true,
				isIndexGo: false,
				currentCeiling: null,
				listInfo: [],
				scrollInfo: {},
				scrollTop: 0.01,
				isOkCurrent: false,
				isShowScroll: true,
				current: 0,
				selectedCity: null,
				scrollToDistrict: false,
			}
		},
		props: {
			letters: {
				type: Array,
				default: () => []
			},
			cityTabs: {
				type: Array,
				default: () => []
			},
			isLetters: {
				type: Boolean,
				default: true
			},
			isIndexToast: {
				type: Boolean,
				default: true
			},
			idValue: {
				type: String,
				default: 'id'
			},
			nameValue: {
				type: String,
				default: 'name'
			},
			currentCity: {
				type: Object,
				default: () => ({})
			},
			isCurrentCity: {
				type: Boolean,
				default: true
			},
			hotCity: {
				type: Array,
				default: () => []
			},
			isHotCity: {
				type: Boolean,
				default: true
			},
			isSearch: {
				type: Boolean,
				default: true
			},
			cityList: {
				type: Object,
				default: () => ({})
			},
			isAvatar: {
				type: Boolean,
				default: false
			},
			avatarValue: {
				type: String,
				default: 'avatar'
			},
			isFu: {
				type: Boolean,
				default: false
			},
			fuValue: {
				type: String,
				default: 'fu'
			},
			isCeil: {
				type: Boolean,
				default: true
			},
			isIndexAc: {
				type: Boolean,
				default: true
			},
			indexAcColor: {
				type: String,
				default: '#5594f9'
			},
			isTop: {
				type: Boolean,
				default: false
			},
			activeTab: {
				type: Number,
				default: 0
			},
			locationCity: {
				type: Object,
				default: () => ({})
			},
		},
		mounted() {
			this.afterConverHH = uni.upx2px(this.indexEachHH);
			this.getLocation();
		},
		watch: {
			activeTab(newVal) {
				this.current = newVal;
				this.isShowScroll = true;
			},
			searchList(newVal) {
				if (newVal.length === 0 && this.scrollToDistrict) {
					this.scrollToCityDistricts();
				}
			},
		},
		methods: {
			changeTab(index) {
				console.log('index', index);
				const selectedTab = this.cityTabs[index];

				// 处理默认区县Tab的点击（id为0时）
				if (selectedTab.id === 0) {
					// 可以添加提示信息或其他逻辑
					uni.showToast({
						title: '请先选择城市',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				if (index !== 0) {
					this.isShowScroll = false;
				} else {
					this.isShowScroll = true;
				}
				this.current = index;
				this.$emit('haoChangeTab', selectedTab.id);
			},

			formatAreaData(item) {
				console.log('item', item);
				const areaNames = item.areaNames ? item.areaNames.split(",") : [];
				const areaIds = item.areaIds ? item.areaIds.split(",") : [];

				// Determine if this is a district (区/县)
				const isDistrict = item.areaLevel === 'district' ||
					item[this.nameValue].includes('区') ||
					item[this.nameValue].includes('县') ||
					(areaNames.length >= 3 && areaNames[2]);

				return {
					areaId: item.areaId || item[this.idValue] || '',
					areaName: isDistrict ? (areaNames[2] || item.areaName || item[this.nameValue] || '') : '',
					cityName: areaNames[1] || item.cityName || '',
					cityCode: areaIds[1] || item.cityCode || '',
					provinceName: areaNames[0] || item.provinceName || '',
					provinceCode: areaIds[0] || item.provinceCode || '',
					areaLevel: isDistrict ? 'district' : 'city'
				};
			},

			scrollToCityDistricts() {
				if (this.scrollToDistrict && this.selectedCity) {
					const cityName = this.selectedCity[this.nameValue] || '';
					if (!cityName) {
						console.warn('无法跳转，选中的城市缺少名称:', this.selectedCity);
						return;
					}

					const firstLetter = cityName.charAt(0).toUpperCase();
					const letterIndex = this.letters.indexOf(firstLetter);

					if (letterIndex !== -1) {
						this.$nextTick(() => {
							setTimeout(() => {
								this.scrollEachId = 'hao-' + firstLetter;
								this.currentCeiling = letterIndex;
								this.scrollToDistrict = false;
							}, 300);
						});
					}
				}
			},

			clickLetters(index) {
				if (this.isIndexGo) {
					// 防止滑动索引时，列表跳转
				}
			},

			goTop() {
				this.scrollTop = 0;
				setTimeout(() => {
					this.scrollTop = 0.01;
				}, 200)
			},

			searchInput() {
				if (this.searchTimeout) {
					clearTimeout(this.searchTimeout)
				}
				if (!this.inputKey) {
					this.searchList = [];
					return
				}

				this.searchTimeout = setTimeout(() => {
					let data = this.cityList;
					let result = [];
					let list = Object.values(data).flat();

					list.forEach(r => {
						const name = r[this.nameValue];
						if (name && name.indexOf(this.inputKey) !== -1) {
							// 补充areaLevel：包含“区/县”则视为区县
							const isDistrict = name.includes('区') || name.includes('县');
							result.push({
								...r,
								[this.nameValue]: name,
								[this.idValue]: r[this.idValue] || '',
								areaLevel: isDistrict ? 'district' : 'city' // 关键：搜索结果的级别判断
							});
						}
					});

					this.searchList = result;
				}, 800)
			},

			getLocation() {
				const that = this;
				uni.createSelectorQuery()
					.in(this)
					.selectAll('.hao-lettersEach')
					.boundingClientRect(rect => {
						if (rect && rect.length > 0) {
							that.indexFirstTT = Math.round(rect[0].top);
							that.indexLastBB = Math.round(rect[rect.length - 1].bottom);
						}
					})
					.exec();

				uni.createSelectorQuery()
					.in(this)
					.select('.hao-scroll')
					.boundingClientRect(rect => {
						that.scrollInfo = rect || {};
					})
					.exec();

				uni.createSelectorQuery()
					.in(this)
					.selectAll('.hao-eachTitle')
					.boundingClientRect(rect => {
						that.listInfo = rect || [];
					})
					.exec();
			},

			listenScroll(e) {
				if (!this.scrollInfo || !this.listInfo || this.listInfo.length === 0) return;

				let top = this.scrollInfo.top || e.target.offsetTop;
				let scrollTop = e.detail.scrollTop;
				let allTop = top + scrollTop;

				if (this.currentCeiling !== null) {
					// 大于最后一个
					if (allTop >= this.listInfo[this.listInfo.length - 1].top) {
						this.currentCeiling = this.listInfo.length - 1;
						return
					} else if (allTop > this.listInfo[this.currentCeiling].top &&
						allTop > this.listInfo[this.currentCeiling + 1].top) {
						let aa = this.listInfo.slice(this.currentCeiling + 1, this.listInfo.length);
						let bb = true;
						aa.some((r, v) => {
							if (allTop < r.top && bb) {
								this.currentCeiling += v;
								bb = false;
							}
						})
						return
					}

					// 当前位置小于之前
					if (allTop < this.listInfo[this.currentCeiling].top) {
						if (allTop < this.listInfo[0].top) {
							this.currentCeiling = null;
						} else {
							let aa = this.listInfo.slice(0, this.currentCeiling).reverse();
							let bb = true;
							aa.some((r, v) => {
								if (allTop >= r.top && bb) {
									this.currentCeiling = this.currentCeiling - v - 1;
									bb = false;
								}
							})
						}
					}
				} else {
					if (allTop >= this.listInfo[0].top && allTop < this.listInfo[1].top) {
						this.currentCeiling = 0;
						if (!this.isOkCurrent) {
							this.isOkCurrent = true;
						}
					} else if (allTop > this.listInfo[0].top && allTop > this.listInfo[1].top) {
						let bb = true;
						this.listInfo.some((r, v) => {
							if (allTop < r.top && bb) {
								this.currentCeiling = v;
								bb = false;
							}
						})
						if (!this.isOkCurrent) {
							this.isOkCurrent = true;
						}
					} else {
						this.currentCeiling = null;
					}
				}
			},

			selectIndex(item) {
				if (!item) return;

				const itemName = item[this.nameValue];
				if (!itemName) {
					console.warn('选择的项缺少名称字段:', item);
					return;
				}

				if (this.searchList.length > 0) {
					this.inputKey = '';
					this.searchList = [];
					this.$emit('citySelected', item);

					const formattedData = this.formatAreaData(item);
					if (formattedData.areaLevel === 'city' || !formattedData.areaLevel) {
						this.$nextTick(() => {
							this.$emit('haoTap', formattedData);
						});
					} else {
						this.$emit('haoTap', formattedData);
					}
				} else {
					this.$emit('haoTap', this.formatAreaData(item));
				}
			},

			handleLetterClick(e, index) {
				this.scrollEachId = 'hao-' + e;
				this.currentCeiling = index;
			},

			handleTouchMove(e) {
				if (this.isOk && this.letters && this.letters.length > 0) {
					this.isOk = false;
					setTimeout(() => {
						if (e.touches[0]) {
							let nowY = Math.round(e.touches[0].pageY);
							if (nowY >= this.indexFirstTT && nowY <= this.indexLastBB) {
								let aa = nowY - this.indexFirstTT;
								let bb = aa / this.afterConverHH;
								let cc = parseInt(bb);

								if (bb > cc) {
									this.toastIndex = this.letters[cc];
									if (this.isIndexGo) {
										this.isIndexGo = false;
										this.currentCeiling = cc;
										this.scrollEachId = 'hao-' + this.letters[cc];
										setTimeout(() => {
											this.toastIndex = '';
										}, 700)
									}
								} else {
									this.toastIndex = this.letters[cc - 1];
									if (this.isIndexGo) {
										this.isIndexGo = false;
										this.currentCeiling = cc - 1;
										this.scrollEachId = 'hao-' + this.letters[cc - 1];
										setTimeout(() => {
											this.toastIndex = '';
										}, 700)
									}
								}
							} else {
								this.toastIndex = '';
							}
						}
						this.isOk = true;
					}, 100)
				}
			},

			handleTouchEnd(e, index) {
				if (this.toastIndex && this.letters && this.letters.length > 0) {
					if (this.isOk) {
						this.scrollEachId = 'hao-' + this.toastIndex;
						this.currentCeiling = index;
						setTimeout(() => {
							this.toastIndex = '';
						}, 700)
					} else {
						this.isIndexGo = true;
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.hao-bigbox {
		position: absolute;
		top: 0;
		left: 0;
		height: 100%;
		width: 100%;
		background-color: #fff;

		/* 搜索 */
		.hao-search {
			width: 100%;
			display: flex;
			padding: 20rpx 24rpx 10rpx;
			box-sizing: border-box;
			align-items: center;
			justify-content: center;
			z-index: 99;

			.hao-searchCent {
				width: 100%;
				height: 72rpx;
				background-color: #F1F1F1;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 36rpx;
				padding: 0 33rpx;
				box-sizing: border-box;

				.hao-searchImg {
					width: 32rpx;
					height: 32rpx;
					margin-right: 25rpx;
				}

				.hao-searchInput {
					flex: 1;
					height: 72rpx;
					font-size: 28rpx;
				}
			}
		}

		/*搜索结果*/
		.hao-searchScroll {
			position: absolute;
			top: 100rpx;
			left: 0;
			width: 100%;
			height: calc(100% - 100rpx);
			background: #fff;
			padding: 0 30rpx;
			box-sizing: border-box;
		}

		// 切换数据tabs
		.titleTabs {
			.tab {
				font-weight: 400;
				font-size: 30rpx;
				color: #666666;
				margin-right: 40rpx;
				padding-bottom: 26rpx;
				position: relative;

				&.active {
					font-weight: 600;
					color: #333333;
				}

				&.active::after {
					content: "";
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					display: block;
					width: 47rpx;
					height: 8rpx;
					background: #2f80ed;
					border-radius: 4rpx;
				}
			}
		}

		/*右侧索引*/
		.hao-letters {
			position: absolute;
			top: 0;
			right: 0;
			width: 60rpx;
			z-index: 6;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.hao-letterTop {
				width: 44rpx;
				height: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #666;
				font-size: 22rpx;
			}

			.hao-lettersEach {
				width: 44rpx;
				height: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #666;
				font-size: 22rpx;
			}

			.hao-lettersEachAc {
				color: #fff;
				border-radius: 50%;
			}
		}

		/*当前索引提示内容*/
		.hao-toastIndex {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 160rpx;
			height: 160rpx;
			line-height: 160rpx;
			text-align: center;
			font-size: 56rpx;
			font-weight: 700;
			border-radius: 20rpx;
			z-index: 6;
			background-color: #ddd;
			color: #fff;
		}


		/* 当前与热门 */
		.hao-modu {
			width: 100%;
			padding: 30rpx 24rpx;
			box-sizing: border-box;
			background-color: #F5F5F5;

			.hao-current {
				width: 100%;
				padding-bottom: 20rpx;
			}

			.hao-hotCity {
				width: 100%;
			}

			.hao-moduTitle {
				width: 100%;
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
				margin-bottom: 16rpx;
			}

			.hao-currentBox {
				width: 100%;
				display: flex;
				align-items: center;

				.hao-currentLs {
					background: #FFFFFF;
					border-radius: 6rpx;
					padding: 15rpx 32rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					box-sizing: border-box;

					.hao-currentImg {
						width: 19rpx;
						height: 23rpx;
						margin-right: 11rpx;
					}

					.hao-currentCity {
						color: #333;
						font-size: 28rpx;
					}
				}
			}

			.hao-hotCityBox {
				width: 100%;
				display: flex;
				align-items: center;
				flex-wrap: wrap;

				.hao-hotEachCity {
					padding: 15rpx 47rpx;
					text-align: center;
					max-width: 130rpx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					color: #333;
					font-size: 28rpx;
					margin: 0 20rpx 20rpx 0;
					background: #FFFFFF;
					border-radius: 6rpx;
				}
			}
		}

		/* 数据列表 */
		.hao-scroll {
			position: absolute;
			width: 100%;
			left: 0;
			background-color: #fff;

			.hao-each {
				width: 100%;

				.hao-eachTitle {
					font-size: 28rpx;
					color: #666666;
					background-color: #F5F5F5;
					padding: 6rpx 26rpx;
					box-sizing: border-box;
					font-weight: 400;
				}

				.hao-second {
					width: 100%;
					padding: 14rpx 26rpx 0;
					box-sizing: border-box;
				}
			}
		}

		/*吸顶*/
		.ceiling {
			position: absolute;
			left: 0;
			width: 100%;
			z-index: 1;
			font-size: 32rpx;
			color: #333;
			background-color: #f4f4f4;
			padding: 10rpx 30rpx;
			box-sizing: border-box;
			font-weight: 600;
		}

		/*搜索结果与列表的每一项*/
		.hao-secondEach {
			width: 100%;
			display: flex;
			align-items: center;
			padding: 15rpx 0;

			.hao-avatar {
				width: 90rpx;
				height: 90rpx;
				margin-right: 20rpx;

				.hao-avatarImg {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}
			}

			.hao-text {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.hao-name {
					font-size: 28rpx;
					color: #333;
				}

				.hao-fu {
					font-size: 24rpx;
					color: #999;
				}
			}
		}

		.hao-secondEach:last-child {
			border-bottom: none;
		}
	}
</style>